package com.eden.task.controller;

import com.eden.common.annotation.Log;
import com.eden.common.config.Global;
import com.eden.common.constant.FileConstants;
import com.eden.common.constant.UserTaskConstants;
import com.eden.common.core.controller.BaseController;
import com.eden.common.core.domain.AjaxResult;
import com.eden.common.core.page.TableDataInfo;
import com.eden.common.enums.BusinessType;
import com.eden.common.utils.StringUtils;
import com.eden.common.utils.file.FileUploadUtils;
import com.eden.common.utils.file.MimeTypeUtils;
import com.eden.common.utils.poi.ExcelUtil;
import com.eden.common.utils.uuid.IdUtils;
import com.eden.framework.util.ShiroUtils;
import com.eden.school.domain.SchoolUser;
import com.eden.school.service.ISchoolUserService;
import com.eden.task.domain.TaskPicture;
import com.eden.task.domain.TaskVideo;
import com.eden.task.domain.UserTask;
import com.eden.task.service.ICheckOpinionService;
import com.eden.task.service.ITaskPictureService;
import com.eden.task.service.ITaskVideoService;
import com.eden.task.service.IUserTaskService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * 用户发布任务Controller
 *
 * @author jiaoyang
 * @date 2020-09-03
 */
@Controller
@RequestMapping("/task/usertask")
public class UserTaskController extends BaseController {
    private String prefix = "task/usertask";

    @Autowired
    private IUserTaskService userTaskService;

    @Autowired
    private ISchoolUserService schoolUserService;

    @Autowired
    private ITaskPictureService taskPictureService;
    @Autowired
    private ITaskVideoService taskVideoService;

    @Autowired
    private ICheckOpinionService checkOpinionService;


    @RequiresPermissions("task:usertask:view")
    @GetMapping()
    public String usertask() {
        return prefix + "/usertask";
    }

    /**
     * 查询用户发布任务审核后通过的列表
     */
    @RequiresPermissions("task:usertask:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(UserTask userTask) {
        userTask.setTaskStatus(UserTaskConstants.CHECK_PASS_STATUS);
        startPage();
        List<UserTask> list = userTaskService.selectUserCheckedTaskList(userTask);
        return getDataTable(list);
    }

    @RequiresPermissions("task:usertask:view")
    @GetMapping("/check")
    public String usertaskcheck() {
        return prefix + "/usertaskcheck";
    }

    /**
     * 查询审核用户发布任务列表
     */
    @RequiresPermissions("task:usertask:list")
    @PostMapping("/checklist")
    @ResponseBody
    public TableDataInfo checklist(UserTask userTask) {
        startPage();
        List<UserTask> list = userTaskService.selectUserTaskList(userTask);
        return getDataTable(list);
    }

    /**
     * 导出用户发布任务列表
     */
    @RequiresPermissions("task:usertask:export")
    @Log(title = "用户发布任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(UserTask userTask) {
        List<UserTask> list = userTaskService.selectUserTaskList(userTask);
        ExcelUtil<UserTask> util = new ExcelUtil<UserTask>(UserTask.class);
        return util.exportExcel(list, "usertask");
    }

    /**
     * 新增用户发布任务
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        //随机生成任务ID
        String uuid = IdUtils.fastSimpleUUID().substring(0, 4);
        String taskId = "T" + uuid + System.currentTimeMillis();
        mmap.put("taskId", taskId);
        return prefix + "/add";
    }

    /**
     * 新增保存用户发布任务
     */
    @RequiresPermissions("task:usertask:add")
    @Log(title = "用户发布任务", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(UserTask userTask) {
        userTask.setTaskStatus(UserTaskConstants.WAIT_CHECK_STATUS);
        userTask.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(userTaskService.insertUserTask(userTask));
    }

    /**
     * 修改用户发布任务
     */
    @GetMapping("/edit/{taskId}")
    public String edit(@PathVariable("taskId") String taskId, ModelMap mmap) {
        UserTask userTask = userTaskService.selectUserTaskById(taskId);
        mmap.put("userTask", userTask);
        return prefix + "/edit";
    }


    /**
     * 审核任务信息详情
     *
     * @param taskId
     * @param mmap
     * @return
     */
    @RequiresPermissions("task:usertask:check")
    @Log(title = "审核用户发布任务", businessType = BusinessType.INSERT)
    @GetMapping("/checkTask/{taskId}")
    public String checkTask(@PathVariable("taskId") String taskId, ModelMap mmap) {
        UserTask userTask = userTaskService.selectUserTaskById(taskId);
        SchoolUser user = new SchoolUser();
        if (StringUtils.isNotNull(userTask) && StringUtils.isNotNull(userTask.getCreateBy()) && !"".equals(userTask.getCreateBy())) {
            user = schoolUserService.selectSchoolUserByLoginName(userTask.getCreateBy());
        }
        if (StringUtils.isNotNull(userTask)) {
            mmap.put("userTask", userTask);
        }
        if (StringUtils.isNotNull(user)) {
            mmap.put("user", user);
        }
        return prefix + "/checkUserTask";
    }


    /**
     * 修改保存用户发布任务
     */
    @RequiresPermissions("task:usertask:edit")
    @Log(title = "用户发布任务", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(UserTask userTask) {
        return toAjax(userTaskService.updateUserTask(userTask));
    }

    /**
     * 删除用户发布任务
     */
    @RequiresPermissions("task:usertask:remove")
    @Log(title = "用户发布任务", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(userTaskService.deleteUserTaskByIds(ids));
    }

    /**
     * 文件上传对应的方法
     *
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadFiles")
    @ResponseBody
    @Transactional
    public AjaxResult uploadFiles(@RequestParam("file") MultipartFile file, @RequestParam("taskId") String taskId, HttpSession session) throws IOException {
        TaskPicture taskPicture = new TaskPicture();
        TaskVideo taskVideo = new TaskVideo();
        int result = 0;
        // 上传文件路径
        String uploadFilePath = Global.getUploadPath();
        //获取文件后缀名
        String extension = FileUploadUtils.getExtension(file);
        //判断文件是否是允许的类型
        if (FileUploadUtils.isAllowedExtension(extension, MimeTypeUtils.IMAGE_VIDEO_TYPE_EXTENSION)) {
            //判断是否是图片类型
            if (FileUploadUtils.isFileTypeExtension(extension, MimeTypeUtils.IMAGE_TYPE_EXTENSION)) {
                // 上传并返回新文件名称
                if (StringUtils.isNotNull(file)) {
                    String picturePath = FileUploadUtils.upload(uploadFilePath, file);
                    String fileName = FileUploadUtils.getFileName(picturePath);
                    taskPicture.setPictureName(fileName);
                    taskPicture.setPictureUrl(picturePath);
                    //设置文件状态
                    taskPicture.setPictureStatus(FileConstants.FILE_USE_STATUS);
                }
                //获取任务ID
                if (StringUtils.isNotNull(taskId) && !"".equals(taskId)) {
                    taskPicture.setTaskCpid(taskId);
                }
                result = taskPictureService.insertTaskPicture(taskPicture);
            }
            //判断是否是视频类型
            if (FileUploadUtils.isFileTypeExtension(extension, MimeTypeUtils.VIDEO_TYPE_EXTENSION)) {
                // 上传并返回新文件名称
                if (StringUtils.isNotNull(file)) {
                    String videoPath = FileUploadUtils.upload(uploadFilePath, file);
                    String fileName = FileUploadUtils.getFileName(videoPath);
                    taskVideo.setVideoName(fileName);
                    taskVideo.setVideoUrl(videoPath);
                    //设置文件状态
                    taskVideo.setVideoStatus(FileConstants.FILE_USE_STATUS);
                }
                //获取任务ID
                if (StringUtils.isNotNull(taskId) && !"".equals(taskId)) {
                    taskVideo.setTaskCvid(taskId);
                }
                result = taskVideoService.insertTaskVideo(taskVideo);
            }
        }
        return toAjax(result);
    }


    /**
     * 审核用户发布任务
     */
    @RequiresPermissions("task:usertask:remove")
    @Log(title = "用户发布任务", businessType = BusinessType.DELETE)
    @PostMapping("/checkUserTask")
    @ResponseBody
    public AjaxResult checkUserTask(UserTask userTask) {
        if (StringUtils.isNotNull(userTask)) {
            userTask.setCheckId(String.valueOf(ShiroUtils.getUserId()));
            userTask.setCheckName(ShiroUtils.getLoginName());
        }
        return toAjax(userTaskService.updateUserTask(userTask));
    }

    /**
     * 审核用户发布任务不通过
     */
    @Log(title = "用户发布任务", businessType = BusinessType.DELETE)
    @GetMapping("/checkTaskNextFlow")
    public String checkTaskNextFlow(String taskId, ModelMap map) {
        map.put("taskId", taskId);
        return prefix + "/checkTaskNextFlow";
    }
}